package com.itianyu.blog.dao.implementations;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itianyu.blog.dao.beans.Page;
import com.itianyu.blog.dao.beans.User;

/**
 * 文章实现类
 * @author wumgji
 */
@Service
public class PageImplementation implements com.itianyu.blog.dao.interfaces.PageInterface {

	private static final long serialVersionUID = 1L;

	@PersistenceContext
	private EntityManager em;

	// 创建文章实体
	public Page createPage() {
		Page page = new Page();
		return page;
	}

	// 保存文章信息
	@Transactional
	public Page savePage(Page page) {
		return em.merge(page);
	}

	// 根据文章ID删除文章信息
	@Transactional
	public void deletePage(int pageId) {
		Page page = em.find(Page.class, pageId);
		if (page != null) {
			em.remove(page);
		}
		return;
	}

	// 根据文章ID查询文章信息
	@Transactional(readOnly = true)
	public Page findPage(int pageId) {
		return em.find(Page.class, pageId);
	}

	// 查询文章列表
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Page> findPageEntities(User user) {
		String str="";
		if(user.getUsername().equals("admin")){
			str="SELECT OBJECT(p) FROM Page p ORDER BY p.menuOrder ASC";
		}
		Query q = em.createQuery(str);
		List<Page> items = q.getResultList();
		return items;
	}

	// 计算文章列表的总数
	@Override
	public int getPageEntitiesCount() {
		Query q = em.createQuery("SELECT COUNT(p) FROM Page p");
		Long num_results = (Long) q.getSingleResult();
		return num_results.intValue();
	}

	// 查询文章列表的标题
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Object[]> findPageTitles() {
		Query q = em.createQuery("SELECT p.menuTitle, p.pageId FROM Page p WHERE p.menuOrder > 0 ORDER BY p.menuOrder ASC");
		List<Object[]> result = q.getResultList();
		return result;
	}

}
